/// <reference types="cypress" />

const BAIDU = 'https://aip.baidubce.com/'
const AK = 'aRGCe0Qhn88NoQCGNlxTbMP3'
const SK = 'tdYkCVPZccMn43g08C1gLcpSlexZi3RK'

/**
 * @description 调用百度文字识别并以保存到文件中
 * @author 许晓波
 * @param ocr_file 验证码图片的路径
 * @param output_file 以 json 格式导出识别后的验证码的文件路径
 */
Cypress.Commands.add('getBaiduOCR', (ocr_file, output_file) => {
  cy.fixture(ocr_file).then(base64 => {
    cy.request({
      method: 'POST',
      url:
        `${BAIDU}oauth/2.0/token?grant_type=client_credentials&client_id=` +
        AK +
        '&client_secret=' +
        SK,
    })
      .its('body.access_token')
      .then(token => {
        cy.request({
          form: true,
          method: 'POST',
          url: `${BAIDU}rest/2.0/ocr/v1/general_basic?access_token=` + token,
          body: {
            image: base64,
          },
        })
          .its('body.words_result.0.words')
          .should('not.be.null')
          .and('have.length', 4)
          .then(code => {
            cy.writeFile(output_file, {
              code: code,
            })
          })
      })
  })
})
